package com.itheima.filter;

import com.itheima.Utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.IOException;
//      @param filterChain 过滤器链
@Slf4j
//@WebFilter(urlPatterns = "/*")
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp,
                         FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        String url = request.getRequestURI().toString();  //1. get the url
        //2.判断url里面包含login，有就放
        if (url.contains("login")){
            filterChain.doFilter(request,response);
            return;
        }
        //3. 获取请求头的令牌
        String headjwt = request.getHeader("token");
        //4. 判断令牌是否为空
        if (!StringUtils.hasLength(headjwt)) {
            // 令牌为空，返回401
          //  response.setStatus(401);
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        //5.解析token,如果解析失败，401
        try {
            JwtUtils.parseJWT(headjwt);
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        //6.解析成功，放行
        log.info("令牌合法, 放行");
        filterChain.doFilter(request,response);
    }
}
